<template>
    <a-modal :title="modal.title" :width="1000" :confirmLoading="submitLoading" :visible="modal.visible" :footer="null" @cancel="close">
        <a-alert
            v-if="enterAccount.payments && enterAccount.payments.length === 0"
            message="温馨提示"
            type="error"
            show-icon
            closable>
            <template #description>
                <label>《{{enterAccount.name}}》还未开户，请联系运营人员尽快开户，否则影响结算发放！任务创建不影响。</label>
            </template>
        </a-alert>
        <a-form-model :model="taskForm" ref="taskForm">
            <a-row :gutter="10">
                <a-col :span="8">
                    <a-form-model-item label="任务名称" prop="fieldTaskName" :rules="[{ required: true, message: '请输入任务名称!' }]">
                        <a-input placeholder="请输入任务名称" v-model="taskForm.fieldTaskName"/>
                    </a-form-model-item>
                </a-col>
                <a-col :span="8">
                    <a-form-model-item label="任务类别" prop="fieldTaskType" :rules="[{ required: true, message: '请选择任务类别!' }]">
                        <a-select v-model="taskForm.fieldTaskType" placeholder="请选择任务类别">
                            <a-select-option v-for="(item,key) in categoryData" :key="key" :value="item.label">{{item.label}}</a-select-option>
                        </a-select>
                    </a-form-model-item>
                </a-col>
                <a-col :span="8">
                    <a-form-model-item label="任务区域" prop="fieldTaskRegion" :rules="[{ required: true, message: '请选择任务区域!' }]">
                        <a-select v-model="taskForm.fieldTaskRegion" @change="cityChange" placeholder="请选择任务区域" show-search :filter-option="filterOption">
                            <a-select-option v-for="(item,key) in cityData" :key="key" :value="item.value">{{item.label}}</a-select-option>
                        </a-select>
                    </a-form-model-item>
                </a-col>
            </a-row>
                        
                     <a-alert
            type="info"
            description="模板协议需关联园区"
            show-icon
            closable>
        </a-alert>
        <a-row :gutter="10">
            <a-col :span="12">
                <a-form-model-item label="园区服务商" prop="fieldTaskPark" :rules="[{ required: true, message: '请选择园区服务商!' }]">
                    <a-select v-model="taskForm.fieldTaskPark" @change="parkOrTempChange" placeholder="请选择园区服务商" show-search :filter-option="filterOption">
                        <a-select-option v-for="(item,key) in parkData" :key="key" :value="item.parkId">{{item.name}}</a-select-option>
                    </a-select>
                </a-form-model-item>
            </a-col>
            <a-col :span="12">
                 <a-form-model-item label="个人&服务商协议（园区服务商关联）" prop="pactTempId" :rules="[{ required: true, message: '请选择模板!' }]">
                    <a-select v-model="taskForm.pactTempId" placeholder="请选择模板">
                        <a-select-option v-for="(item,key) in tempData" :key="key" :value="item.id">{{item.name}}</a-select-option>
                    </a-select>
                </a-form-model-item>
            </a-col>
        </a-row>
                
                    <a-alert
            type="info"
            description="报名人员有限制，导包人员不限制"
            show-icon
            closable>
        </a-alert>
                    <a-form-model-item label="需要人数" prop="fieldTaskPeopleNumber" :rules="[{ required: true, message: '请输入需要人数!' }]">
                        <a-input-number style="width: 300px;" placeholder="请输入需要人数" :min="1" :step="1" v-model="taskForm.fieldTaskPeopleNumber"/>
                    </a-form-model-item>
             <a-alert
            type="info"
            description="当前时间超出执行结束日期，任务将终止，小程序任务也终止"
            show-icon
            closable>
        </a-alert>
            <a-row :gutter="10">
                <a-col :span="12">
                    <a-form-model-item label="执行开始日期" prop="fieldTaskStartDate" :rules="[{ required: true, message: '选择执行开始日期!' }]">
                        <a-date-picker show-time v-model="taskForm.fieldTaskStartDate" style="width: 100%;" value-format="YYYY-MM-DD HH:mm:ss" />
                    </a-form-model-item>
                </a-col>
                <a-col :span="12">
                     <a-form-model-item label="执行结束日期" prop="fieldTaskEndDate" :rules="[{ required: true, message: '选择执行结束日期!' }]">
                        <a-date-picker show-time v-model="taskForm.fieldTaskEndDate" style="width: 100%;" value-format="YYYY-MM-DD HH:mm:ss" />
                    </a-form-model-item>
                </a-col>
            </a-row>
             <a-alert
            type="info"
            description="价格区间，小程序报名价格需在区间范围内"
            show-icon
            closable>
        </a-alert>
            <a-row :gutter="10">
                <a-col :span="12">
                    <a-form-model-item label="任务开始价格" prop="fieldTaskStartPrice" :rules="[{ required: true, message: '输入任务价格!' }]">
                                <a-input-number placeholder="请输入任务价格" style="width:100%" v-model="taskForm.fieldTaskStartPrice" :min="1" :max="100000" :parser="(value)=>{
                    let reg = /^(-)*(\d+)\.(\d\d).*$/;
                    return value.replace(/\s?|(,*)/g, '').replace(reg,'$1$2.$3');
                }"/>
                            </a-form-model-item>
                </a-col>
                 <a-col :span="12">
                    <a-form-model-item label="任务结束价格" prop="fieldTaskEndPrice" :rules="[{ required: true, message: '输入任务结束价格!' }]">
                        <a-input-number placeholder="请输入任务结束价格" style="width:100%" v-model="taskForm.fieldTaskEndPrice" :min="1" :max="100000" :parser="(value)=>{
            let reg = /^(-)*(\d+)\.(\d\d).*$/;
            return value.replace(/\s?|(,*)/g, '').replace(reg,'$1$2.$3');
        }"/>
                    </a-form-model-item>
                </a-col>
            </a-row>
                    
                   
                            
                            
                    <a-form-model-item label="需求描述" prop="fieldTaskDescription" :rules="[{ required: true, message: '输入需求描述!' }]">
                        <a-input type="textarea" :rows="3" :maxlength="180" placeholder="请输入需求描述" v-model="taskForm.fieldTaskDescription"/>
                        <span class="nums-len">还可以输入{{taskFormNum.fieldTaskDescription - taskForm.fieldTaskDescription.length}}字</span>
                    </a-form-model-item>
                    <a-form-model-item label="报名要求" prop="fieldTaskEnroll" :rules="[{ required: true, message: '输入报名要求!' }]">
                        <a-input type="textarea" :rows="3" :maxlength="180" placeholder="请输入报名要求" v-model="taskForm.fieldTaskEnroll"/>
                         <span class="nums-len">还可以输入{{taskFormNum.fieldTaskEnroll - taskForm.fieldTaskEnroll.length}}字</span>
                    </a-form-model-item>
                    <a-form-model-item label="交付要求" prop="fieldTaskDeliver" :rules="[{ required: true, message: '输入交付要求!' }]">
                        <a-input type="textarea" :rows="3" :maxlength="180" placeholder="请输入交付要求" v-model="taskForm.fieldTaskDeliver"/>
                         <span class="nums-len">还可以输入{{taskFormNum.fieldTaskDeliver - taskForm.fieldTaskDeliver.length}}字</span>
                    </a-form-model-item>
        </a-form-model>
        <div class="custom-drawer-footer">
            <a-button key="back" @click="close">取消</a-button>
            <a-button type="primary" @click="submitTask('taskForm')">保存任务</a-button>
        </div>
    </a-modal>
</template>
<script>
import { mapGetters } from 'vuex'
import store from '@/store'
import moment from "moment"
import { 
    allOnlineTaskAdd,
    allOnlineTaskEdit
} from '@/api/manage/task'
import { 
  allGetSginRelation
} from '@/api/manage/sign'
import {
    TASK_CATEGORY_DATA
} from './form'
import {
    CITY_DATA
} from '@/config/baseData'
export default {
    name: 'taskAdd',
    data () {
        return {
            taskForm:{
                pactTempId:'',
                fieldTaskName:'',
                fieldTaskPark:'',
                fieldTaskType:'',
                fieldTaskRegion:'',
                fieldTaskPeopleNumber:'',
                fieldTaskEndDate:'',
                fieldTaskPrice:'',
                fieldTaskStartPrice:'',
                fieldTaskEndPrice:'',
                fieldTaskDescription:'',
                fieldTaskEnroll:'',
                fieldTaskDeliver:''
            },
            taskFormNum:{
                fieldTaskDescription:180,
                fieldTaskEnroll:180,
                fieldTaskDeliver:180,
            },
            modal:{
                title:'新建任务',
                visible:false,
                id:''
            },
            areaName:'',
            parkData:[],
            tempData:[],
            categoryData:TASK_CATEGORY_DATA,
            cityData:CITY_DATA,
            submitLoading:false
        }
    },
    watch: {
        taskForm: {
        handler(cval, oval) {
            if (cval.fieldTaskDescription.length > this.taskFormNum.fieldTaskDescription) {
                this.taskForm.fieldTaskDescription = String(cval.fieldTaskDescription).slice(0, this.taskFormNum.fieldTaskDescription);
            }
            if (cval.fieldTaskEnroll.length > this.taskFormNum.fieldTaskEnroll) {
                this.taskForm.fieldTaskEnroll = String(cval.fieldTaskEnroll).slice(0, this.taskFormNum.fieldTaskEnroll);
            }
            if (cval.fieldTaskDeliver.length > this.taskFormNum.fieldTaskDeliver) {
                this.taskForm.fieldTaskDeliver = String(cval.fieldTaskDeliver).slice(0, this.taskFormNum.fieldTaskDeliver);
            }
        },
        deep: true
        }
    },
    computed: {
        ...mapGetters(['taskField','userInfo','enterAccount'])
    },
    methods:{
        add(item){
            const {taskForm,modal} = this;
            for(var keys in taskForm){
                taskForm[keys] = '';
            }
            modal.id = '';
            modal.title = '新建任务';
            if(item != true && Object.keys(item.dynamicFields).length !=0){
                Object.assign(taskForm,item.dynamicFields);
                this.taskForm.pactTempId = item.pactTempId;
                this.taskForm.fieldTaskStartDate = moment(item.dynamicFields.fieldTaskStartDate);
                this.taskForm.fieldTaskEndDate = moment(item.dynamicFields.fieldTaskEndDate);
                const priceArr = item.dynamicFields.fieldTaskPrice.split('-');
                taskForm.fieldTaskStartPrice = priceArr[0];
                taskForm.fieldTaskEndPrice = priceArr[1];
                modal.id = item.id;
                modal.title = '编辑任务';
            }
            this.modal.visible = true;
            this.initSelect();
        },
        async initSelect(){
            let params = {enterpriseId:this.userInfo.relationId}
            const {data} = await store.dispatch('getEnterpriseOrParkEnabled',params);
                data && data.forEach(v=>{
                v.value = v.parkId;
                v.label = v.name;
            })
            this.parkData = data;
        },
        filterOption(input, option) {
            return (
                option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
            );
        },
        async parkOrTempChange(parkId){
            const {data} = await allGetSginRelation(parkId);
            this.tempData = data.protocol;
        },
        cityChange(value){
            if(value){
                const obj = CITY_DATA.find(v=>v.value === value);
                this.areaName = obj.label;
            }else{
                this.areaName = '';
            }
        },
        submitTask(formName){
            this.$refs[formName].validate(async valid => {
                if (valid) {
                    let params = {};

                    if(this.taskForm.fieldTaskEndDate < this.taskForm.fieldTaskStartDate){
                        return this.$message.error('执行结束时间不能小于执行开始时间！');
                    }
                    if(this.taskForm.fieldTaskEndPrice < this.taskForm.fieldTaskStartPrice){
                        return this.$message.error('区间结束价格不能小于区间开始价格！');
                    }

                    let dynamicFields = [];
                    this.taskField.forEach(v => {
                        for(var keys in this.taskForm){
                            if(v.fieldCode.indexOf(keys) != -1){
                                if(v.fieldCode === 'fieldTaskPrice'){
                                    const price = this.taskForm.fieldTaskStartPrice +'-'+ this.taskForm.fieldTaskEndPrice;
                                    dynamicFields.push({taskConId:v.taskConId,value:price})
                                }else{
                                    dynamicFields.push({taskConId:v.taskConId,value:this.taskForm[keys]})
                                }
                            }
                        }
                    });
                    params.name= this.taskForm.fieldTaskName;
                    params.pactTempId = this.taskForm.pactTempId;
                    params.parkId= this.taskForm.fieldTaskPark;
                    params.category= this.taskForm.fieldTaskType;
                    params.startTime= moment(this.taskForm.fieldTaskStartDate).format('YYYY-MM-DD HH:mm:ss');
                    params.endTime= moment(this.taskForm.fieldTaskEndDate).format('YYYY-MM-DD HH:mm:ss');
                    params.cityCode= this.taskForm.fieldTaskRegion;
                    params.cityName = this.areaName;
                    params.personNumber = this.taskForm.fieldTaskPeopleNumber;
                    params.dynamicFields = dynamicFields;
                    if(this.modal.id){
                        params.id = this.modal.id;
                    }
                    this.submitLoading = true;
                    const {code,data} = this.modal.id ? await allOnlineTaskEdit(params) : await allOnlineTaskAdd(params);
                    this.submitLoading = false;
                    if(code === '1'){
                        this.$message.success('操作成功');
                        this.modal.visible = false;
                        this.$emit("on-ok");
                    }
                }else{
                    return false;
                }
            })
        },
        close(){
            this.modal.visible = false;
        }
    }
}
</script>
<style>
    .nums-len{
        float: right;
    line-height: 1.1;
    color: #999;
    }
</style>